package mongo_utils

import (
	"context"
	"log"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func ConnectToMongoDB(uri string) (*mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		log.Println(err)
		return nil, err
	}

	err = client.Ping(ctx, nil)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	log.Println("Successfully connected to MongoDB!")
	return client, nil
}

func GetCurrentOp(client *mongo.Client) (interface{}, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	result := client.Database("admin").RunCommand(ctx, map[string]interface{}{"currentOp": 1})
	if result.Err() != nil {
		log.Println(result.Err())
		return nil, result.Err()
	}

	var res interface{}
	err := result.Decode(&res)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	return res, nil

}

func CurrentOpHandler(currentOp interface{}) map[string]int {
	var calc_map = make(map[string]int)
	if data, ok := currentOp.(primitive.D); ok {
		inprog := data[0].Value
		for _, v := range inprog.(primitive.A) {
			if data1, ok := v.(primitive.D); ok {
				if data1[4].Key == "client" {
					var client = data1[4].Value.(string)
					host := strings.Split(client, ":")[0]
					calc_map[host] += 1
				}
			}
		}
	}
	return calc_map
}
